//
//  WBStatusListViewModel.swift
//  Weibo
//
//  Created by 伏文东 on 2018/1/24.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import Foundation


/// 上拉刷新最大尝试次数
private let maxPullupTrTimes = 3
class WBStatusListViewModel {
    
    lazy var statusList = [WBStatus]()
    /// 上拉刷新错误次数
    private var pullupErrorTimes = 0
    /// 加载微博列表
    ///
    /// - Parameters:
    ///   - pullup: 是否上拉刷新标记
    ///   - completion: 完成回调[网络请求是否成功
    func loadStatus(pullup: Bool, completion: @escaping(_ isSuccess: Bool, _ shouldRefresh: Bool) -> ())  {
        
        // 判断是否是上拉刷新 同时检查刷新错误
        if pullup && pullupErrorTimes > maxPullupTrTimes {
            completion(false, false)
            return
        }
        
        // since_id 下拉刷新，取出数组中第一条微博的 id
        let since_id = pullup ? 0 : (statusList.first?.id ?? 0)
        
        let max_id = pullup ? (statusList.last?.id ?? 0) : 0
        
        WBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
               completion(isSuccess, false)
                return
            }
            // FIXME: 拼接数据
            
            if pullup {
                self.statusList += array
            } else {
                self.statusList = array + self.statusList
            }
            
            if pullup && array.count == 0 {
                self.pullupErrorTimes += 1
                completion(isSuccess, false)
            } else {
                completion(isSuccess, true)
            }
        }
    }
}
